/**
 * Copyright (C), 2018 store
 * Encoding: UTF-8
 * Date: 20-5-13 下午12:22
 * History:
 */
package com.swak.frame.job;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import com.swak.frame.exception.SwakRuntimeException;
import com.swak.frame.logger.SwakLoggerFactory;
import com.swak.frame.timer.HashedWheelTimer;
import com.swak.frame.timer.Timeout;
import com.swak.frame.timer.Timer;
import com.swak.frame.timer.TimerTask;
import com.swak.frame.timer.WheelTimerHolder;

/**
 * 本地数据刷新 ClassName: RefreshTaskJob.java
 * 
 * @author colley.ma
 * @date 2021年3月29日 下午12:07:51
 */
public abstract class RefreshTaskJob implements RefreshConfigurable, TimerTask, InitializingBean {

    protected Logger logger = SwakLoggerFactory.getLogger(this.getClass());

    private HashedWheelTimer hashedWheelTimer;

    private RefreshRate refreshRate;

    /** 获取数据 **/
    public abstract void doTask();

    @Override
    public void run(Timeout timeout) throws Exception {
        try {
            this.refresh();
        } catch (Exception e) {
            logger.error("run  Refresh Job error", e);
        }
        reput(timeout, refreshRate.getRate());
    }

    private void reput(Timeout timeout, Long tick) {
        if ((timeout == null) || (tick == null)) {
            throw new IllegalArgumentException();
        }
        Timer timer = timeout.timer();
        if (timer.isStop() || timeout.isCancelled()) {
            return;
        }
        timer.newTimeout(timeout.task(), tick, TimeUnit.SECONDS);
    }

    @Override
    public void clear() {

    }

    @Override
    public void refresh() {
        doTask();
    }

    @Override
    public String cacheName() {
        return this.getClass().getName();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.hashedWheelTimer == null) {
            this.hashedWheelTimer = WheelTimerHolder.refreshableWheel();
        }

    }

    /**
     * @Desc 启动定时刷新缓存任务
     * @param
     * @return void
     */
    @Override
    public void startJob() {
        if (refreshRate == null) {
            throw new SwakRuntimeException(
                this.getClass().getName() + " swakJob config is illegal cron is null,fixedRate<=0");
        }
        logger.warn("Start {} TaskJob Timer...", this.getClass().getSimpleName());
        this.hashedWheelTimer.newTimeout(this, 1, TimeUnit.MINUTES);
        logger.warn("Start {} Timer successfully", this.getClass().getSimpleName());
    }

    @Override
    public void setRefreshRate(RefreshRate refreshRate) {
        if (this.refreshRate == null) {
            this.refreshRate = refreshRate;
        }
    }
}
